<template>
    <div style="height: 100%; width: 100%">
        <div id="container" :style="styleObj"></div>

        <div class="configBtn">
            <el-button @click="showConfig">
                {{$t('maps.offlineBaiduMap.config')}}
            </el-button>

            <el-button @click="showDownload">
                {{$t('maps.offlineBaiduMap.download')}}
            </el-button>
        </div>

        <el-dialog
                :title="$t('maps.offlineBaiduMap.title')"
                :visible="isConfigShow"
                :before-close="handleClose" center>

            <el-form label-width="150px" label-position="right"
                     class="demo-form-inline" style="width: 95%">

                <el-form-item :label="$t('maps.offlineBaiduMap.center')">
                    <el-input v-model="center"></el-input>
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.zoom')">
                    <el-input v-model="zoom"></el-input>
                </el-form-item>

                <!--<el-form-item :label="$t('maps.offlineBaiduMap.downloadMinZoom')">-->
                <!--<el-input v-model="downloadMinZoom"></el-input>-->
                <!--</el-form-item>-->

                <el-form-item :label="$t('maps.offlineBaiduMap.downloadMaxZoom')">
                    <el-input v-model="downloadMaxZoom"></el-input>
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.styleJson')">
                    <el-input auto-complete="off" v-model="styleJson"
                              clearable type="textarea" resize="none"
                              :rows="10"
                              :autosize="{minRows: 10, maxRows: 10 }"
                              style="margin-top: 10px;"></el-input>
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.node')">
                    <p v-html="$t('maps.offlineBaiduMap.nodeTip')" style="line-height: 20px;"></p>
                </el-form-item>

                <el-form-item>
                    <el-button @click="handleConfig">{{$t('common.btn_ok')}}</el-button>
                    <el-button @click="handleClose">{{$t('common.btn_cancel')}}</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog
                :title="$t('maps.offlineBaiduMap.titleDownload')"
                :visible="isDownloadShow"
                :before-close="handleDownloadClose" center>

            <el-form label-width="150px" label-position="right"
                     class="demo-form-inline" style="width: 95%">

                <el-form-item :label="$t('maps.offlineBaiduMap.center')">
                    {{center}}
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.zoom')">
                    {{zoom}}
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.downloadMaxZoom')">
                    {{downloadMaxZoom}}
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.zoomdatadesc')">
                    <el-table :data="zoomdatadesc" height="300">
                        <el-table-column :label="$t('maps.offlineBaiduMap.zoomLevel')"
                                         prop="zoomLevel" width="60"></el-table-column>
                        <el-table-column :label="$t('maps.offlineBaiduMap.imgCount')"
                                         prop="totalCount" width="200"></el-table-column>
                        <el-table-column :label="$t('maps.offlineBaiduMap.singleImgSize')"
                                         prop="singleImgSize" width="120"></el-table-column>
                        <el-table-column :label="$t('maps.offlineBaiduMap.totalSize')"
                                         prop="totalSize">
                            <template slot-scope="scope">
                                {{scope.row.totalSize + ' (' +scope.row.totalSizeUnit + ')'}}
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.allDataSize')">
                    {{allParams.totalSize + ' (' +allParams.totalSizeUnit + ')'}}
                </el-form-item>

                <el-form-item :label="$t('maps.offlineBaiduMap.url')">
                    {{url}}
                </el-form-item>

                <el-form-item>
                    <el-button @click="handleDownload">{{$t('maps.offlineBaiduMap.addToDownloadTask')}}</el-button>
                    <el-button @click="handleDownloadClose">{{$t('common.btn_cancel')}}</el-button>
                </el-form-item>

            </el-form>
        </el-dialog>
    </div>
</template>

<script>
  import 'echarts/map/js/china.js'
  import 'echarts/map/js/world.js'
  import 'echarts/extension/bmap/bmap'

  import {deepCopyArray, deepCopyObj} from '@/utils/objectUtils'
  import {mapOption} from './mapOption'
  import {findAllTiles_2} from './getDownloadUrls'

  import fs from 'fs';
  import request from 'request';
  import path from 'path'

  export default {
    name: 'offlineBaiduMap',
    data() {
      return {
        msg: '地图离线下载工具',

        styleObj: {
          width: '100%',
          height: 0,
          paddingTop: 0
        },

        loading: null,

        myChart: null,
        default_center: [113.962342, 22.543714],

        isConfigShow: false,
        isDownloadShow: false,

        center: '',
        zoom: 10,
        // downloadMinZoom: 10,
        downloadMaxZoom: 18,
        styleJson: '',

        zoomdatadesc: [],
        url: '',
        allParams: {},
        styleStr: ''
      }
    },

    created: function () {
    },

    methods: {
      initEchart() {
        this.myChart = this.$echarts.init(document.getElementById("container"));

        var option = deepCopyArray(mapOption);

        option.bmap.center = this.default_center;

        option.series[0].symbolSize = function (val) {
          return val[2] / 10;
        }

        if (option && typeof option === "object") {
          this.myChart.setOption(option, true);
        }

        this.center = option.bmap.center.join(',');
        this.zoom = option.bmap.zoom;
        this.styleJson = JSON.stringify(option.bmap.mapStyle.styleJson);
      },

      resetSize() {
        let fullHeight = document.getElementById("loadPageDiv").offsetHeight;
        let dialogHeaderTitleHeight = document.getElementById("dialogHeaderTitle").offsetHeight;
        this.styleObj.height = fullHeight - dialogHeaderTitleHeight + 'px';
      },

      showConfig() {
        this.isConfigShow = true;
      },

      handleClose() {
        this.isConfigShow = false;
      },

      checkIsNum(str) {
        if (str == '' || str == null || typeof str == 'undefined' || isNaN(str)) {
          return false;
        }
        return true;
      },

      handleConfig() {
        if (this.center.indexOf(',') < 0) {
          this.$message.error(this.$t('maps.offlineBaiduMap.centerError'));
          return;
        }
        let center = this.center.split(',');
        if (!this.checkIsNum(center[0]) || !this.checkIsNum(center[1])) {
          this.$message.error(this.$t('maps.offlineBaiduMap.centerError'));
          return;
        }

        if (!this.checkIsNum(this.zoom)) {
          this.$message.error(this.$t('maps.offlineBaiduMap.zoomError'));
          return;
        }

        if (!this.checkIsNum(this.downloadMaxZoom)) {
          this.$message.error(this.$t('maps.offlineBaiduMap.downloadMaxZoomError'));
          return;
        }

          this.downloadMaxZoom = parseInt(this.downloadMaxZoom);
          this.zoom = parseInt(this.zoom);

        if(this.downloadMaxZoom > 18){
            this.$message.error(this.$t('maps.offlineBaiduMap.downloadMaxZoomError'));
            return;
        }


        console.log(this.downloadMaxZoom+ '--' + (typeof this.downloadMaxZoom));
        console.log(this.zoom+ '--' + (typeof this.zoom));
        console.log((this.downloadMaxZoom < this.zoom));

        if (this.downloadMaxZoom < this.zoom) {
          this.$message.error(this.$t('maps.offlineBaiduMap.downloadZoomError'));
          return;
        }

        try {
          let styleJson = JSON.parse(this.styleJson);
        } catch (e) {
          this.$message.error(this.$t('maps.offlineBaiduMap.styleJsonError'));
          return;
        }

        this.resetOptionWithConfig();

        this.isConfigShow = false;
      },

      resetOptionWithConfig() {
        let center = this.center.split(',');
        var styleJson = JSON.parse(this.styleJson);
        var option = this.myChart.getOption();

        option.bmap[0].center = center;
        option.bmap[0].zoom = this.zoom;
        option.bmap[0].mapStyle.styleJson = styleJson;

        if (option && typeof option === "object") {
          this.myChart.setOption(option, true);
        }
      },

      showDownload() {
        this.resetOptionWithConfig();
        var map = this.myChart.getModel().getComponent('bmap').getBMap();
        var data = findAllTiles_2(map, this.zoom, this.downloadMaxZoom);
        this.styleStr = map.D.w_.styleStr;
        this.zoomdatadesc = data[0];
        this.allParams = data[1];

        this.isDownloadShow = true;
      },
      handleDownloadClose() {
        this.isDownloadShow = false;
      },

      handleDownload() {
        this.openFullScreen('maps.offlineBaiduMap.loadingDownload');
        // 添加下载任务
        this.createDownloadTask();
        // 跳转下载页面

        this.loading.close();
        this.isDownloadShow = false;
      },

      openFullScreen(str) {
        this.loading = this.$loading({
          lock: true,
          text: this.$t(str),
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      },

      createDownloadTask() {
        let downloadTaskConf_BasicsDir = './static/downloadTaskConf/';
        let taskConf_Path = downloadTaskConf_BasicsDir + 'downloadtasks.data';

        // 判断文件是否被使用
        if(this.$store.getters.fileIsLocked){
          let that = this;
          setTimeout(()=>{
            that.createDownloadTask();
          }, 500);

          return;
        }
        // 给文件加锁
        this.$store.dispatch('setFileIsLocked', true);

        let that = this;
        try {
          // 1.读取原有的任务配置文件，由JSON，转数组
          fs.readFile(taskConf_Path, 'utf8', function (err, data) {
            if (err){
              that.$store.dispatch('setFileIsLocked', false);
              that.$message.error(this.$t('maps.offlineBaiduMap.getTasksConfigError'));
              return false;
            }

            var oldTask = JSON.parse(data);

            // 2.创建新的下载任务
            // 任务名称
            let timelong = new Date().getTime();
            let name = that.$t('maps.offlineBaiduMap.tasksName') + timelong;
            let dataFileName = timelong;
            let dataSize = that.allParams.totalSize;
            let dataSizeUnit = that.allParams.totalSizeUnit;
            let taskAddTime = timelong;

            oldTask.push({
              taskName: name,
              taskAddTime: taskAddTime,
              taskStatus: 'stop',
              dataSize: dataSize,
              dataSizeUnit: dataSizeUnit,
              dataFileName: dataFileName,
              downloadDir: '',
              progress: 0,
            });

            // 3.将下载任务写入文件
            fs.writeFile(taskConf_Path, JSON.stringify(oldTask), function (err) {
              if (err) {
                that.$store.dispatch('setFileIsLocked', false);
                that.$message.error(this.$t('maps.offlineBaiduMap.addTasksError'));
                return false;
              }
            });

            // 4.创建下载任务具体数据文件
            let taskDescConfFullPath = downloadTaskConf_BasicsDir + dataFileName;

            var taskDescData = [];
            var taskIndex = 0;
            let hearder = 'http://api0.map.bdimg.com/customimage/tile?';
            let urlMiddel = '&udt=20181025&scale=1&ak=';
            let styleJson = JSON.parse(that.styleJson);

            taskDescData.push({
              index : taskIndex,
              hearder : hearder,
              urlMiddel: urlMiddel,
              styleJson: that.styleStr,
              zoomdatadesc: that.zoomdatadesc,
              totalCount: that.allParams.totalCount,
              currentDownload:{}
            });

            // 5.将下载任务具体信息写入文件
            fs.writeFile(taskDescConfFullPath, JSON.stringify(taskDescData), function (err) {
              if (err) {
                that.$store.dispatch('setFileIsLocked', false);
                that.$message.error(this.$t('maps.offlineBaiduMap.addTasksError'));
                return false;
              }
            });

          });

        } catch (e) {
          that.$store.dispatch('setFileIsLocked', false);
          that.$message.error(this.$t('maps.offlineBaiduMap.addTasksError'));
          return false;
        }

        this.$message.success(this.$t('maps.offlineBaiduMap.addTasksSuccess'));
        // 给文件解锁
        this.$store.dispatch('setFileIsLocked', false);
        return true;
      },

    },

    mounted: function () {
      this.resetSize();
      this.initEchart();
    }
  }
</script>

<style scoped>
    .configBtn {
        position: absolute;
        top: 60px;
        left: 20px;
        font-weight: 800;
    }

    /** 隐藏左下角的百度标识 */
    >>> .anchorBL {
        display: none
    }

    >>> .el-form-item {
        margin-bottom: 5px;
    }
</style>
